/**
 * Created by Tuffy on 16/6/6.
 */
'use strict';

adminCtrl

    .controller('LiftTruckListCtrl', ['$rootScope', '$scope', '$state', '$modal', 'AreaService', function ($rootScope, $scope, $state, $modal, AreaService) {
        // 查询条件
        $scope.waybillInfo = {
            departProvinceCode: null,
            departCityCode: null,
            receiptProvinceCode: null,
            receiptCityCode: null,
            beginCreateTime: null,
            endCreateTime: null
        }

        // 查询条件区域数据
        $scope.loadProvince = [];

        // 加载发车市
        $scope.departCity = [];

        // 加载到达市
        $scope.receiptCity = [];

        // 设置模态窗口
        var myOtherModal = $modal({
            scope: $scope,
            title: '提车人信息',
            placement: 'center',
            templateUrl: $rootScope.Context.path + '/templates/components/lift-view.html',
            show: false
        });

        // 加载省数据
        function loadProvince() {
            AreaService.loadProvince()
                .success(function (result) {
                    if (result.success) {
                        $scope.loadProvince = result.data;
                    }
                });
        };

        // 根据省编码查询发车市
        $scope.loadDepartCity = function () {
            AreaService.loadCityByCode($scope.waybillInfo.departProvinceCode)
                .success(function (result) {
                    if (result.success) {
                        $scope.departCity = result.data;
                    }
                });
        };

        // 根据省编码查询收车市
        $scope.loadReceiptCity = function () {
            AreaService.loadCityByCode($scope.waybillInfo.receiptProvinceCode)
                .success(function (result) {
                    if (result.success) {
                        $scope.receiptCity = result.data;
                    }
                });
        }

        // 显示模态窗口
        $scope.showLiftModal = function () {
            myOtherModal.$promise.then(myOtherModal.show);
        }

        // 加载省数据
        loadProvince();
    }])


    .controller('LaborPriceImportCtrl', ['$rootScope', '$scope', '$modal', 'LaborPriceImportService', 'FileUploader', function ($rootScope, $scope, $modal, LaborPriceImportService, FileUploader) {

        var uploader = $scope.uploader = new FileUploader({
            url: '/upload/excel',
            fileName: 'file'
        });
        // a sync filter
        uploader.filters.push({
            name: 'syncFilter',
            fn: function (item /*{File|FileLikeObject}*/, options) {
                // console.log('syncFilter');
                return this.queue.length < 10;
            }
        });
        // CALLBACKS

        uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
            // console.info('onWhenAddingFileFailed', item, filter, options);
        };
        uploader.onAfterAddingFile = function (fileItem) {
            fileItem.upload();
            // console.info('onAfterAddingFile', fileItem);
        };
        uploader.onAfterAddingAll = function (addedFileItems) {
            // console.info('onAfterAddingAll', addedFileItems);
        };
        uploader.onBeforeUploadItem = function (item) {
            // console.info('onBeforeUploadItem', item);
        };
        uploader.onProgressItem = function (fileItem, progress) {
            // console.info('onProgressItem', fileItem, progress);
        };
        uploader.onProgressAll = function (progress) {
            // console.info('onProgressAll', progress);
        };
        uploader.onSuccessItem = function (fileItem, response, status, headers) {
            // console.info('onSuccessItem', fileItem, response, status, headers);
        };
        uploader.onErrorItem = function (fileItem, response, status, headers) {
            // console.info('onErrorItem', fileItem, response, status, headers);
        };
        uploader.onCancelItem = function (fileItem, response, status, headers) {
            // console.info('onCancelItem', fileItem, response, status, headers);
        };
        uploader.onCompleteItem = function (fileItem, response, status, headers) {

            // console.info('onCompleteItem', fileItem, response, status, headers);
            layer.msg(response.message);
            $scope.laborPriceInfo.batchId = response.data;
            $scope.loadExcelData(response.data);
        };
        uploader.onCompleteAll = function () {
            // console.info('onCompleteAll');
        };

        // console.info('uploader', uploader);

        $scope.laborPriceInfo = {
            id: '',
            routeName: '',
            originProvinceName: '',
            originAreaName: '',
            originCityName: '',
            destProvinceName: '',
            destAreaName: '',
            destCityName: '',
            miles: '',
            currentValue: '',
            validateResultCodeString: '',
            validateResultCode: '',
            effectiveDate: '',
            batchId:''
        };

        function cl() {
            $scope.laborPriceInfo = {
                id: '',
                routeName: '',
                originProvinceName: '',
                originAreaName: '',
                originCityName: '',
                destProvinceName: '',
                destAreaName: '',
                destCityName: '',
                miles: '',
                currentValue: '',
                validateResultCodeString: '',
                validateResultCode: '',
                effectiveDate: '',
                batchId:''
            };
        }

        // 当前对象
        $scope.userTruckObj = {
            pageNo: 1,
            pageSize: 10,
            loadMore: function ($event, pageNo) {
                this.pageNo = pageNo;
                if ((this.pageNo > $scope.page.totalPage)) {
                    $event.stopPropagation();
                    this.pageNo = $scope.page.totalPage;
                    return;
                } else if (this.pageNo < 1) {
                    $event.stopPropagation();
                    this.pageNo = 1;
                    return;
                }
                $scope.loadExcelData();
            }
        };

        //
        $scope.loadExcelData = function (data) {
            LaborPriceImportService.loadExcelData({
                pageNo: $scope.userTruckObj.pageNo,
                pageSize: $scope.userTruckObj.pageSize,
                batchId:data
            }).success(function (result) {
                if (result.success) {
                    $scope.laborList = result.data.list;
                    $scope.page = result.data.page;
                    buildPage();
                } else {
                    layer.msg(result.message || '数据加载异常');
                }
            });
        };

        function buildPage() {
            $scope.item = [];
            var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5 ? ($scope.userTruckObj.pageNo == 1 ? (parseInt($scope.userTruckObj.pageNo) + 5) : (parseInt($scope.userTruckObj.pageNo) + 5)) : $scope.page.totalPage;
            var start = $scope.userTruckObj.pageNo > 5 ? ($scope.userTruckObj.pageNo == 1 ? (parseInt($scope.userTruckObj.pageNo) - 5) : (parseInt($scope.userTruckObj.pageNo) - 5)) : 1;
            for (var i = start; i <= end; i++) {
                $scope.item.push(i);
            }
        };

        var laborPriceUpdateModal = $modal({
            scope: $scope,
            title: '劳务价格修改',
            placement: 'center',
            templateUrl: $rootScope.Context.path + '/templates/ils/dialog/labor-price-update-view.html',
            show: false
        });

        // 显示修改窗体
        $scope.showUpdateDlg = function (item) {
            cl();
            LaborPriceImportService.getById({
                id: item.id
            }).success(function (result) {
                if (result.success) {
                    $scope.laborPriceInfo = result.data;
                    laborPriceUpdateModal.$promise.then(laborPriceUpdateModal.show);
                } else {
                    layer.msg(result.message || '加载数据异常');
                }
            });
        };

        $scope.update = function () {
            delete $scope.laborPriceInfo.updateTime;
            delete $scope.laborPriceInfo.createTime;
            $scope.laborPriceInfo.effectiveDate = $scope.laborPriceInfo.effectiveDate == '' ? "" : typeof ($scope.laborPriceInfo.effectiveDate) == 'string' ? $scope.laborPriceInfo.effectiveDate : $scope.laborPriceInfo.effectiveDate.format("yyyy-MM-dd 00:00:00");
            LaborPriceImportService.update($scope.laborPriceInfo).success(function (result) {
                if (result.success) {
                    $scope.loadExcelData($scope.laborPriceInfo.batchId);
                    laborPriceUpdateModal.$promise.then(laborPriceUpdateModal.hide);
                    layer.msg(result.message || '修改成功');
                } else {
                    layer.msg(result.message || '更新数据异常');
                }
            });
        }


        $scope.del = function (item) {
            var index = layer.confirm('确定删除该数据？', {
                btn: ['确定', '取消'], //按钮,
                skin: 'admin-confirm-btn-class',
                title: '提示'
            }, function () {
                layer.close(index);
                if (item.id == '') {
                    layer.msg('删除标识不能为空');
                    return false;
                }
                LaborPriceImportService.del({id: item.id, batchId:$scope.laborPriceInfo.batchId}).success(function (result) {
                    if (result.success) {
                        layer.msg(result.message || '删除成功');
                        $scope.loadExcelData($scope.laborPriceInfo.batchId);
                    } else {
                        layer.msg(result.message || '删除数据异常');
                    }
                });
            });
        };


        $scope.deleteAll = function () {
            var index = layer.confirm('确定取消导入？', {
                btn: ['确定', '取消'], //按钮,
                skin: 'admin-confirm-btn-class',
                title: '提示'
            }, function () {
                layer.close(index);
                window.location.reload();

                // LaborPriceImportService.deleteAll().success(function (result) {
                //     if (result.success) {
                //         layer.msg(result.message || '取消导入成功');
                //         $scope.loadExcelData();
                //     } else {
                //         layer.msg(result.message || '取消导入异常');
                //     }
                // });
            });
        };

        $scope.importData = function (item) {
            var index = layer.confirm('确定导入？', {
                btn: ['确定', '取消'], //按钮,
                skin: 'admin-confirm-btn-class',
                title: '提示'
            }, function () {
                layer.close(index);
                if (item.validateResult != null) {
                    layer.msg('导入数据有错误不能导入！');
                    return false;
                }
            LaborPriceImportService.importData({batchId:$scope.laborPriceInfo.batchId}).success(function (result) {
                if (result.success) {
                    $scope.loadExcelData($scope.laborPriceInfo.batchId);
                    layer.msg(result.message || '导入成功');
                } else {
                    layer.msg(result.message || '导入数据异常');
                }
            });
            });
        };

    }])